package com.vogue.supplymall.order.controller;

import com.vogue.supplymall.common.domain.dto.ControllerResultInfo;
import com.vogue.supplymall.common.domain.dto.EditCartInfo;
import com.vogue.supplymall.common.domain.dto.OrderInfo;
import com.vogue.supplymall.common.domain.dto.UserInfo;
import com.vogue.supplymall.common.domain.tool.MessageSourceUtils;
import com.vogue.supplymall.order.common.CheckCartUtils;
import com.vogue.supplymall.order.domain.biz.CartBiz;
import com.vogue.supplymall.order.exception.AddCartException;
import com.vogue.supplymall.order.exception.InsufficientInventoryException;
import com.vogue.supplymall.order.exception.OverMaxCountException;
import com.vogue.supplymall.order.exception.OverMaxProductCountException;
import com.vogue.supplymall.order.exception.RemoveCartException;
import com.vogue.supplymall.order.exception.UpdateCartException;
import com.vogue.supplymall.order.exception.AddCarItemCheckException;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * The type Cart controller.
 *
 * @aouthor: zhangliang
 * @date: Create in 2018-01-09
 */
@RestController
public class CartController extends BaseController {
    /**
     * The constant log.
     */
    public static final Logger log = LoggerFactory.getLogger(CartController.class);

    @Resource
    private CartBiz cartBiz;
    @Resource
    private MessageSourceUtils messageSourceUtils;

    /**
     * Gets cart.
     * 获取当前用户的购物车
     *
     * @param appver the appver
     * @return the cart
     */
    @RequestMapping(value = "/is/{appver}/order/cart/get", method = RequestMethod.POST)
    public ResponseEntity<Object> getCart(@PathVariable("appver") String appver) {
        log.info("get cart start ");
        EditCartInfo editCartInfo = new EditCartInfo();
        UserInfo info = new UserInfo();
        if (SecurityUtils.getSubject().isAuthenticated()) {
            info = (UserInfo) SecurityUtils.getSubject().getPrincipal();
            editCartInfo.setLoginId(info.getLoginId());
            if (null != info.getOrganInfo()) {
                editCartInfo.setOrganid(info.getOrganInfo().getId());
            }
            editCartInfo.setSyscodeid(info.getSyscodeid());
        } else {
            log.info("获取登信息失败！");
        }

        ControllerResultInfo resultInfo = new ControllerResultInfo();
        resultInfo.setData(cartBiz.findCart(editCartInfo,info));
        log.info("get cart end ");
        return new ResponseEntity<>(resultInfo, HttpStatus.OK);
    }

    /**
     * Add cart response entity.
     * 根据商品id添加商品进购物车
     *
     * @param appver       the appver
     * @param editCartInfo the edit cart info
     * @return the response entity
     */
    @RequestMapping(value = "/is/{appver}/order/cart/add", method = RequestMethod.POST)
    public ResponseEntity<Object> addCart(@PathVariable("appver") String appver, @RequestBody EditCartInfo editCartInfo) {
        log.info("add product to cart start ");
        UserInfo info = new UserInfo();
        if (SecurityUtils.getSubject().isAuthenticated()) {
            info = (UserInfo) SecurityUtils.getSubject().getPrincipal();
            editCartInfo.setSyscodeid(info.getSyscodeid());
            editCartInfo.setLoginId(info.getLoginId());
            if (null != info.getOrganInfo()) {
                editCartInfo.setOrganid(info.getOrganInfo().getId());
            }
            editCartInfo.setTel(info.getTel());
            log.info("获取登信息：" + info.getLoginId());
            if (CheckCartUtils.checkAddCartParameter(editCartInfo, info.getOrganInfo() == null ? 0 : info.getLoginUserType())) {
                log.info(" 参数错误！ ");
                throw new AddCartException("parameter error");
            }
        } else {
            log.info("获取登信息失败！");
        }

        try {
            cartBiz.addCart(editCartInfo, info);
        } catch (InsufficientInventoryException ex) {
            log.info(" method addCart() throw exception, add cart failed .cause: Insufficient Inventory");
            throw new InsufficientInventoryException("");
        } catch (OverMaxCountException ex) {
            log.info(" method addCart() throw exception, add cart failed .cause: cart over max count");
            throw new OverMaxCountException("");
        } catch (OverMaxProductCountException e) {
            log.info(" method addCart() throw exception, cause: OverMaxProductCountException");
            throw e;
        } catch (AddCarItemCheckException e) {
            log.info(" method addCart() throw exception, cause: car item Units need the same");
            throw e;
        } catch (RuntimeException ex) {
            log.info(" method addCart() throw exception, add cart failed");
            throw new AddCartException("");
        }
        log.info("购物车已添加！");
        ControllerResultInfo resultInfo = new ControllerResultInfo();
        resultInfo.setResult(true);
        resultInfo.setData(cartBiz.findCartCount(editCartInfo));
        resultInfo.setMsg(messageSourceUtils.getMessage("2603", new String[]{}));
        log.info("add product to cart end ");
        return new ResponseEntity<>(resultInfo, HttpStatus.OK);
    }

    /**
     * Update cart response entity.
     * 更新购物车-编辑购物车时使用
     *
     * @param appver       the appver
     * @param editCartInfo the edit cart info
     * @return the response entity
     */
    @RequestMapping(value = "/is/{appver}/order/cart/update", method = RequestMethod.POST)
    public ResponseEntity<Object> updateCart(@PathVariable("appver") String appver, @RequestBody EditCartInfo editCartInfo) {
        log.info("update cart start ");

        if (SecurityUtils.getSubject().isAuthenticated()) {
            UserInfo info = (UserInfo) SecurityUtils.getSubject().getPrincipal();
            log.info("获取登信息：" + info.getLoginId());
            if (CheckCartUtils.checkUpdateCartParameter(editCartInfo, info.getOrganInfo() == null ? 0 : info.getLoginUserType())) {
                log.info(" 参数错误！ ");
                throw new UpdateCartException("parameter error");
            }
        } else {
            log.info("获取登信息失败！");
        }

        try {
            cartBiz.updateCart(editCartInfo);
        } catch (InsufficientInventoryException ex) {
            log.info(" method addCart() throw exception, add cart failed .cause: Insufficient Inventory");
            throw new InsufficientInventoryException("");
        } catch (RuntimeException ex) {
            log.info(" method updateCart() throw exception, modify cart failed");
            throw new UpdateCartException("");
        }
        log.info("购物车已更新！");
        ControllerResultInfo resultInfo = new ControllerResultInfo();
        resultInfo.setResult(true);
        resultInfo.setMsg(messageSourceUtils.getMessage("2604", new String[]{}));
        log.info("update cart end ");
        return new ResponseEntity<>(resultInfo, HttpStatus.OK);
    }

    /**
     * Update cart response entity.
     * 批量更新购物车-编辑购物车时使用
     *
     * @param appver           the appver
     * @param editCartInfoList the edit cart info list
     * @return the response entity
     */
    @RequestMapping(value = "/is/{appver}/order/cart/updatelist", method = RequestMethod.POST)
    public ResponseEntity<Object> updateCartList(@PathVariable("appver") String appver, @RequestBody List<EditCartInfo> editCartInfoList) {
        log.info("update cart start ");

        if (SecurityUtils.getSubject().isAuthenticated()) {
            UserInfo info = (UserInfo) SecurityUtils.getSubject().getPrincipal();
            log.info("获取登信息：" + info.getLoginId());
            for (EditCartInfo editCartInfo : editCartInfoList) {
                if (CheckCartUtils.checkUpdateCartParameter(editCartInfo, info.getOrganInfo() == null ? 0 : info.getLoginUserType())) {
                    log.info(" 参数错误！ ");
                    throw new UpdateCartException("parameter error");
                }
            }
        } else {
            log.info("获取登信息失败！");
        }

        try {
            cartBiz.updateCartList(editCartInfoList);
        } catch (InsufficientInventoryException ex) {
            log.info(" method addCart() throw exception, add cart failed .cause: Insufficient Inventory");
            throw new InsufficientInventoryException("");
        } catch (RuntimeException ex) {
            log.info(" method updateCart() throw exception, modify cart failed");
            throw new UpdateCartException("");
        }
        log.info("购物车已更新！");
        ControllerResultInfo resultInfo = new ControllerResultInfo();
        resultInfo.setResult(true);
        resultInfo.setMsg(messageSourceUtils.getMessage("2604", new String[]{}));
        log.info("update cart end ");
        return new ResponseEntity<>(resultInfo, HttpStatus.OK);
    }

    /**
     * Remove cart response entity.
     * 删除购物车中的商品
     *
     * @param appver       the appver
     * @param editCartInfo the edit cart info
     * @return the response entity
     */
    @RequestMapping(value = "/is/{appver}/order/cart/remove", method = RequestMethod.POST)
    public ResponseEntity<Object> removeMultiCart(@PathVariable("appver") String appver, @RequestBody EditCartInfo editCartInfo) {
        log.info("remove cart start ");
        if (CheckCartUtils.checkRemoveCartParameter(editCartInfo)) {
            log.info(" 参数错误！ ");
            throw new UpdateCartException("parameter error");
        }

        if (SecurityUtils.getSubject().isAuthenticated()) {
            UserInfo info = (UserInfo) SecurityUtils.getSubject().getPrincipal();
            log.info("获取登信息：" + info.getLoginId());
        } else {
            log.info("获取登信息失败！");
        }

        try {
            cartBiz.removeCart(editCartInfo);
        } catch (RuntimeException ex) {
            log.info(" method removeMultiCart() throw exception, modify cart failed");
            throw new RemoveCartException("");
        }
        log.info("购物车已更新！");
        ControllerResultInfo resultInfo = new ControllerResultInfo();
        resultInfo.setResult(true);
        resultInfo.setMsg(messageSourceUtils.getMessage("2605", new String[]{}));
        log.info("remove cart end ");
        return new ResponseEntity<>(resultInfo, HttpStatus.OK);
    }


    /**
     * Again add order response entity.
     * 再次够买按钮
     *
     * @param appver    the appver
     * @param orderInfo the order info
     * @return the response entity
     */
    @RequestMapping(value = "/is/{appver}/order/cart/again", method = RequestMethod.POST)
    public ResponseEntity<Object> againAddOrder(@PathVariable("appver") String appver, @RequestBody OrderInfo orderInfo) {
        log.info("Again Add Order start >>>>>> ");
        UserInfo info = new UserInfo();
        if (SecurityUtils.getSubject().isAuthenticated()) {
            info = (UserInfo) SecurityUtils.getSubject().getPrincipal();
            if (null == orderInfo.getAgainBuyFlag() ||
                    null == orderInfo.getGoodsData()) {
                log.info(" 参数错误！ ");
                throw new UpdateCartException("parameter error");
            }
        } else {
            log.info("获取登信息失败！");
        }

        try {
            cartBiz.againAddCart(orderInfo, info);
        } catch (InsufficientInventoryException ex) {
            log.info(" method addCart() throw exception, add cart failed .cause: Insufficient Inventory");
            throw new InsufficientInventoryException("");
        } catch (OverMaxCountException ex) {
            log.info(" method addCart() throw exception, add cart failed .cause: over max count");
            throw new OverMaxCountException("");
        } catch (AddCarItemCheckException e) {
            log.info(" method addCart() throw exception, cause: car item Units need the same");
            throw e;
        } catch (RuntimeException ex) {
            log.info(" method addCart() throw exception, add cart failed");
            throw new AddCartException("");
        }

        ControllerResultInfo resultInfo = new ControllerResultInfo();
        resultInfo.setResult(true);
        /* 返回订单提交成功 */
        resultInfo.setMsg(messageSourceUtils.getMessage("2605", new String[]{}));
        log.info(" <<<<<< Again Add Order end");
        return new ResponseEntity<>(resultInfo, HttpStatus.OK);
    }


    /**
     * Cart move watch response entity.
     * 购物车移入关注
     *
     * @param appver       the appver
     * @param editCartInfo the edit cart info
     * @return the response entity
     */
    @RequestMapping(value = "/is/{appver}/order/cart/move/watch", method = RequestMethod.POST)
    public ResponseEntity<Object> cartMoveWatch(@PathVariable("appver") String appver, @RequestBody EditCartInfo editCartInfo) {
        log.info("cart Move Watch start ");
        if (CheckCartUtils.checkRemoveCartParameter(editCartInfo) ||
                null == editCartInfo.getProductId() ||
                StringUtils.isEmpty(editCartInfo.getPname())) {
            log.info(" 参数错误！ ");
            throw new UpdateCartException("parameter error");
        }

        UserInfo info = new UserInfo();
        if (SecurityUtils.getSubject().isAuthenticated()) {
            info = (UserInfo) SecurityUtils.getSubject().getPrincipal();
            log.info("获取登信息：" + info.getLoginId());
        } else {
            log.info("获取登信息失败！");
        }

        try {
            cartBiz.cartMoveWatch(editCartInfo, info);
        } catch (RuntimeException ex) {
            log.info(" method cartMoveWatch() throw exception, modify cart failed");
            throw new UpdateCartException("");
        }
        log.info("购物车已更新！");
        ControllerResultInfo resultInfo = new ControllerResultInfo();
        resultInfo.setResult(true);
        resultInfo.setMsg(messageSourceUtils.getMessage("2605", new String[]{}));
        log.info("cart Move Watch end ");
        return new ResponseEntity<>(resultInfo, HttpStatus.OK);
    }


    /**
     * Gets cart.
     * 获取当前用户的购物车的数量
     *
     * @param appver the appver
     * @return the cart
     */
    @RequestMapping(value = "/is/{appver}/order/cart/get/count", method = RequestMethod.POST)
    public ResponseEntity<Object> getCartCount(@PathVariable("appver") String appver) {
        log.info("get cart count start ");
        EditCartInfo editCartInfo = new EditCartInfo();
        if (SecurityUtils.getSubject().isAuthenticated()) {
            UserInfo info = (UserInfo) SecurityUtils.getSubject().getPrincipal();
            editCartInfo.setLoginId(info.getLoginId());
            if (null != info.getOrganInfo()) {
                editCartInfo.setOrganid(info.getOrganInfo().getId());
            }
            editCartInfo.setSyscodeid(info.getSyscodeid());
        } else {
            log.info("获取登信息失败！");
        }

        ControllerResultInfo resultInfo = new ControllerResultInfo();
        resultInfo.setData(cartBiz.findCartCount(editCartInfo));
        log.info("get cart count end ");
        return new ResponseEntity<>(resultInfo, HttpStatus.OK);
    }
}
